from google.appengine.api import urlfetch
from BeautifulSoup import BeautifulStoneSoup
import urllib
import PIL
import PIL.Image
import PIL.ImageOps
import StringIO

ENDPOINT = "http://api.flickr.com/services/rest/"
API_KEY = "bce442cfd26e3f51e1d30207672cdaff"
MIN_PHOTOS = 10 # minimum number of photos to retrieve from stream

class Photostream(object):
    def __init__(self, nsid):
        self.nsid = nsid
        self.photos = []
        
    def get_photo_id(self, index):
        if index >= len(self.photos):
            params = {
                'method':'flickr.people.getPublicPhotos',
                'api_key':API_KEY,
                'user_id':self.nsid,
                'per_page':max(MIN_PHOTOS, (index + 1))
                }
            response = urlfetch.fetch(ENDPOINT + "?" + urllib.urlencode(params)).content
            soup = BeautifulStoneSoup(response)
            self.photos = list([photo['id'] for photo in soup('photo')])
        if index < len(self.photos):
            return self.photos[index]
        return None
    
    def get_photo_url(self, photo_id, size):
        params = {
        'method':'flickr.photos.getSizes',
        'api_key':API_KEY,
        'photo_id':photo_id
        }
        soup = BeautifulStoneSoup(urlfetch.fetch(ENDPOINT + "?" + urllib.urlencode(params)).content)
        sizes = soup('size', {'label':size})
        if not sizes: return None
        return sizes[0]['source']
    
    def fetch_image(self, index, size, border_width=10, border_color='white'):
        photo_id = self.get_photo_id(index)
        if not photo_id: return None
        url = self.get_photo_url(photo_id, size)
        if not url: return None
       
        image = PIL.Image.open(StringIO.StringIO(urlfetch.fetch(url).content)).convert("RGBA")
        image = PIL.ImageOps.expand(image, border=int(border_width), fill=border_color)
        return image
